package lv.solcraft.replication.server.model;

import net.sf.json.JSONNull;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONUtils;

import org.springframework.util.Assert;

import com.sleepycat.persist.model.KeyField;
import com.sleepycat.persist.model.Persistent;

@Persistent(version = 2)
public class Field {

    public static final String NULL = "<NULL>";

    @KeyField(1)
    private String name;

    @KeyField(2)
    private String value;

    protected Field() {
    }

    public Field(String name, String value) {
        super();
        Assert.hasText(name, "Field name can not be null or empty: " + name);
        this.name = name.trim();
        this.value = value == null ? NULL : value;
    }

    public String getName() {
        return name;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value == null ? NULL : value;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        final Field other = (Field) obj;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return name;
    }

    public static Field create(JSONObject jsonField) {
        String value = null;
        if (!JSONUtils.isNull(jsonField.opt("value")))
            value = jsonField.optString("value", null);
        return new Field(jsonField.getString("name"), value);
    }

    public JSONObject toJSON() {
        JSONObject json = new JSONObject();
        json.put("name", name);
        json.put("value", value == null || NULL.equals(value) ? JSONNull.getInstance() : value);
        return json;
    }
}
